#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

#include "mylog.h"

FILE * lfp = NULL;
static const char * mypath = NULL;

static const char * lv_lables[] = {"\xE2\x98\x85 [FATAL]","\xE2\x98\x86 [ERROR]", "[LOG]", "[DEBUG]"};

int mylogon(const char * path)
{
	assert(lfp == NULL);
	if(strcmp(path, "stdout") == 0){
		lfp = stdout;
	}else if(strcmp(path, "stderr") == 0){
		lfp = stderr;
	}else{
		lfp = fopen(path, "a+");
		if(lfp == NULL){
			return -1;
		}
	}
	mypath = path;
	return 0;
}

int mylogoff()
{
	if(strcmp(mypath, "stdout") == 0 || strcmp(mypath, "stderr") == 0){
		return 0;
	}
	return fclose(lfp);
}

int mylogit(unsigned char level, const char *fmt, ...)
{
	if(lfp == NULL || level > LV_DEBUG){
		return -1;
	}
	if(level > MY_LOG_LEVEL){
		return 0;
	}
	fprintf(lfp, "%s", lv_lables[level]);

	time_t t = time(NULL);
	struct tm tm;
	localtime_r(&t, &tm);
	fprintf(lfp, "[%.2d:%.2d:%.2d %.2d/%.2d][%u]: ", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_mon+1, tm.tm_mday, getpid());
	va_list argp;
	va_start(argp, fmt);
	vfprintf(lfp, fmt, argp);
	va_end(argp);
	fprintf(lfp, "\n");
	return 0;
}
